package org.jeecg.common.util;


import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.system.entity.TemplateData;
import org.jeecg.modules.system.entity.WxMssVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
@Slf4j

public class PushWxMessage {
    @Autowired
    private RestTemplate restTemplate;
    private static  final  String appid ="wx49b3a96f172a0d5f";
    private static  final  String appsecret ="64e35357e467047fd90bc0e578c5d755";
    /*
     * 获取access_token
     *
     *  */
    public String getAccess_token() {

        //获取access_token
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + appid + "&secret=" + appsecret;
        String json = restTemplate.getForObject(url, String.class);
        com.alibaba.fastjson.JSONObject myJson = com.alibaba.fastjson.JSONObject.parseObject(json);
        return myJson.get("access_token").toString();
    }
    /**
     * @param openid     用户openid
     * @param templateId 模板ID
     * @return
     */
    public String pushOneUser(String openid, String templateId, Map<String, TemplateData> data) {
        String access_token = getAccess_token();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token;
        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openid);//用户openid
        wxMssVo.setTemplate_id(templateId);//模版id
        wxMssVo.setData(data);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        log.info("小程序推送结果={}", responseEntity.getBody());
        return responseEntity.getBody();
    }

}
